package com.taoym.voucher.job.job;

import com.alibaba.fastjson.JSON;
import com.taoym.voucher.common.constant.CommonConstant;
import com.taoym.voucher.common.response.AccessTokenResp;
import com.taoym.voucher.common.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @coder taoym
 * @datetime 2021/7/14 14:59
 * @desc
 */
@Slf4j
@DisallowConcurrentExecution
public class AccessTokenJob extends QuartzJobBean {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap jobDataMap = jobExecutionContext.getMergedJobDataMap();

        String response = HttpClientUtils.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + jobDataMap.get("appId").toString() + "&secret=" + jobDataMap.get("appSecret").toString());
        log.info("AccessToken {}", response);
        AccessTokenResp accessTokenResp = JSON.parseObject(response, AccessTokenResp.class);
        redisTemplate.opsForValue().set(CommonConstant.ACCESS_TOKEN_KEY, accessTokenResp, accessTokenResp.getExpires_in() - 200, TimeUnit.SECONDS);
    }
}
